package com.lanyun.framework.filter;

import com.lanyun.common.constant.Constants;
import com.lanyun.common.core.domain.saas.vo.SysUserVO;
import org.apache.shiro.SecurityUtils;
import org.apache.shiro.web.filter.PathMatchingFilter;

import javax.servlet.ServletRequest;
import javax.servlet.ServletResponse;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import java.util.Objects;

/**
 *@Description 平台登录路径匹配过滤器
 *@Author Jack.Zou
 *@Date 2021/7/17 9:43
 *@since:
 *@copyright:  版权所有2022 开源组织 gitee(https://gitee.com/walster)作者：Jack.Zou<br/>
 *
 */
public class PlatformLoginPathMatchFilter extends PathMatchingFilter {

    @Override
    public boolean onPreHandle(ServletRequest req, ServletResponse resp, Object mappedValue) throws Exception
    {
        HttpServletRequest request = (HttpServletRequest) req;
        HttpServletResponse response = (HttpServletResponse) resp;
        String servletPath = request.getServletPath();
        Object obj = SecurityUtils.getSubject().getPrincipal();
        if (Objects.isNull(obj)) {
            //如果是登录地址不拦截，否则跳转登录页
            if (Constants.PLATFORM_LOGIN_URL.equals(servletPath)) {
                return super.onPreHandle(request, response, mappedValue);
            }else {
                response.sendRedirect(request.getContextPath() + Constants.PLATFORM_LOGIN_URL);
                return false;
            }
        } else {
            if (obj instanceof SysUserVO) { //SaaS用户
                // 如果请求的路径与平台登录地址相同，则直接放行并跳回SaaS首页
                if (servletPath.contains(Constants.PLATFORM)) {
                    response.sendRedirect(request.getContextPath());
                    return false;
                }
                return super.onPreHandle(request, response, mappedValue);
            }
            return super.onPreHandle(request, response, mappedValue);
        }
    }
}
